﻿using Dapper;
using OMG.Fill.Frunit.Model;
using OMG.Fill.Frunit.Model.Ent;
using OMG.Fill.Frunit.Service;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.Linq;
namespace OMG.Fill.Frunit.Services
{
    /// <summary>
    /// 填报生成记录表T_GenerateLog通用操作类
    /// </summary>
    public class GenerateLogServices : GenerateLogs
    {
        public Pager<List<GenerateLogModel>> GetPageList(GenerateLogQuery query)
        {
            Pager<List<GenerateLogModel>> obj = new Pager<List<GenerateLogModel>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            if (!string.IsNullOrEmpty(query.CreateYear))
            {
                strWhereSql += "and CreateYear = @CreateYear ";
                paramlist.Add("CreateYear", query.CreateYear);
            }
            if (!string.IsNullOrEmpty(query.Cycle))
            {
                strWhereSql += "and Cycle = @Cycle ";
                paramlist.Add("Cycle", query.Cycle);
            }
            if (!string.IsNullOrEmpty(query.TableCode))
            {
                strWhereSql += "and TableCode = @TableCode ";
                paramlist.Add("TableCode", query.TableCode);
            }
            string strFromSql = "from dbo.T_GenerateLog where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<GenerateLogModel>(strSql, paramlist).ToList();
                    foreach (var item in obj.rows)
                    {
                        item.CreateYearName = string.IsNullOrEmpty(item.CreateYear) ? "" : DataDict.Instance["ReportYear"][item.CreateYear];
                        item.CycleName = string.IsNullOrEmpty(item.Cycle) ? "" : DataDict.Instance["ReportCycle"][item.Cycle];
                        switch (item.Cycle)
                        {
                            case "1":
                                item.CycleValueName = item.CreateYearName;
                                break;
                            case "4":
                                item.CycleValueName = string.IsNullOrEmpty(item.Cycle) ? "" : DataDict.Instance["QuarterCycleValue"][item.CycleValue];
                                break;
                            case "12":
                                item.CycleValueName = string.IsNullOrEmpty(item.Cycle) ? "" : DataDict.Instance["MonthCycleValue"][item.CycleValue];
                                break;
                        }

                        item.ReportLevelName = string.IsNullOrEmpty(item.ReportLevel) ? "" : DataDict.Instance["ReportLevel"][item.ReportLevel];
                        item.TableCodeName = string.IsNullOrEmpty(item.TableCode) ? "" : DataDict.Instance["ReportTableName"][item.TableCode];
                        item.StrCreateTime = item.CreateTime == null ? "" : item.CreateTime.Value.ToString("yyyy-MM-dd hh:ss:mm");
                    }
                    obj.total = dbCon.Query<int>(strTotal, paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取填报生成记录表T_GenerateLog分页列表失败", ex);
                return obj;
            }
        }
        public override ResResult<int> AddInfo(GenerateLogEntity model)
        {
            AreaServices areaService = new AreaServices();
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_GenerateLog";
            strSql += "(";
            strSql += "Id,";
            strSql += "TableName,";
            strSql += "TableCode,";
            strSql += "CreateYear,";
            strSql += "Cycle,";
            strSql += "CycleValue,";
            strSql += "CreateTime,";
            strSql += "ReportLevel)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@TableName,";
            strSql += "@TableCode,";
            strSql += "@CreateYear,";
            strSql += "@Cycle,";
            strSql += "@CycleValue,";
            strSql += "@CreateTime,";
            strSql += "@ReportLevel)";

            #region 数据新增部分业务代码
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                model.Id = CustomFun.GetGuid();
                string strCycleValue = "";
                strCycleValue = string.IsNullOrEmpty(model.Cycle) ? "" : DataDict.Instance["ReportCycle"][model.Cycle];
                switch (model.Cycle)
                {
                    case "1":
                        strCycleValue = DataDict.Instance["ReportYear"][model.CreateYear];
                        break;
                    case "4":
                        strCycleValue = string.IsNullOrEmpty(model.Cycle) ? "" : DataDict.Instance["QuarterCycleValue"][model.CycleValue];
                        break;
                    case "12":
                        strCycleValue = string.IsNullOrEmpty(model.Cycle) ? "" : DataDict.Instance["MonthCycleValue"][model.CycleValue];
                        break;
                }
                if (DataDict.Instance["ReportYear"][model.CreateYear] != strCycleValue)
                {
                    strCycleValue = DataDict.Instance["ReportYear"][model.CreateYear] + strCycleValue;
                }
                model.TableName = "(" + DataDict.Instance["ReportLevel"][model.ReportLevel] + DataDict.Instance["ReportCycle"][model.Cycle] + "填报)" + strCycleValue + DataDict.Instance["ReportTableName"][model.TableCode];
                model.CreateTime = DateTime.Now;
                if (!CheckGenerate(model))
                {
                    try
                    {
                        List<ReportEntity> reportList = new List<ReportEntity>();
                        ReportEntity reportModel = new ReportEntity();
                        List<string> areaCodeList = new List<string>();
                        switch (model.ReportLevel)
                        {
                            case "1"://县级
                                areaCodeList = areaService.GetCountyList();
                                break;
                            case "2"://州(市)级
                                areaCodeList = areaService.GetPrefectureList();
                                break;
                            case "3"://全部
                                areaCodeList = areaService.GetProvinceList();
                                break;
                            default:
                                break;
                        }
                        foreach (string code in areaCodeList)
                        {
                            switch (model.Cycle)
                            {
                                case "1":
                                    reportModel = new ReportEntity();
                                    reportModel.Id = CustomFun.GetGuid();
                                    reportModel.AreaCode = code;
                                    reportModel.AddTime = DateTime.Now;
                                    reportModel.FillInYear = model.CreateYear;
                                    reportModel.GenerateId = model.Id;
                                    reportModel.ReportCode = model.TableCode;
                                    reportModel.ReportName = DataDict.Instance["ReportYear"][model.CreateYear] + DataDict.Instance["ReportTableName"][model.TableCode];
                                    reportModel.TimesCycle = model.CreateYear;
                                    reportModel.TimesType = model.Cycle;
                                    reportModel.Status = "1";
                                    reportList.Add(reportModel);
                                    break;
                                case "4":
                                    if (model.CycleValue == "0")
                                    {
                                        for (int i = 1; i <= 4; i++)
                                        {
                                            reportModel = new ReportEntity();
                                            reportModel.Id = CustomFun.GetGuid();
                                            reportModel.AreaCode = code;
                                            reportModel.AddTime = DateTime.Now;
                                            reportModel.FillInYear = model.CreateYear;
                                            reportModel.GenerateId = model.Id;
                                            reportModel.ReportCode = model.TableCode;
                                            reportModel.TimesCycle = i.ToString() + "季度";
                                            //reportModel.TimesCycle = i.ToString();
                                            reportModel.ReportName = DataDict.Instance["ReportYear"][model.CreateYear] + reportModel.TimesCycle + DataDict.Instance["ReportTableName"][model.TableCode];
                                            reportModel.TimesType = model.Cycle;
                                            reportModel.Status = "1";
                                            reportList.Add(reportModel);
                                        }
                                    }
                                    else
                                    {
                                        reportModel = new ReportEntity();
                                        reportModel.Id = CustomFun.GetGuid();
                                        reportModel.AreaCode = code;
                                        reportModel.AddTime = DateTime.Now;
                                        reportModel.FillInYear = model.CreateYear;
                                        reportModel.GenerateId = model.Id;
                                        reportModel.ReportCode = model.TableCode;
                                        reportModel.TimesCycle = model.CycleValue + "季度";
                                       // reportModel.TimesCycle = model.CycleValue;
                                        reportModel.ReportName = DataDict.Instance["ReportYear"][model.CreateYear] + reportModel.TimesCycle + DataDict.Instance["ReportTableName"][model.TableCode];
                                        reportModel.TimesType = model.Cycle;
                                        reportModel.Status = "1";
                                        reportList.Add(reportModel);
                                    }

                                    break;
                                case "12":
                                    if (model.CycleValue == "0")
                                    {
                                        for (int i = 1; i <= 12; i++)
                                        {
                                            reportModel = new ReportEntity();
                                            reportModel.Id = CustomFun.GetGuid();
                                            reportModel.AreaCode = code;
                                            reportModel.AddTime = DateTime.Now;
                                            reportModel.FillInYear = model.CreateYear;
                                            reportModel.GenerateId = model.Id;
                                            reportModel.ReportCode = model.TableCode;
                                            reportModel.TimesCycle = i.ToString().Length == 1 ? "0" + i.ToString() + "月" : i.ToString() + "月";
                                            reportModel.ReportName = DataDict.Instance["ReportYear"][model.CreateYear] + reportModel.TimesCycle + DataDict.Instance["ReportTableName"][model.TableCode];
                                            reportModel.TimesType = model.Cycle;
                                            reportModel.Status = "1";
                                            reportList.Add(reportModel);
                                        }
                                    }
                                    else
                                    {
                                        reportModel = new ReportEntity();
                                        reportModel.Id = CustomFun.GetGuid();
                                        reportModel.AreaCode = code;
                                        reportModel.AddTime = DateTime.Now;
                                        reportModel.FillInYear = model.CreateYear;
                                        reportModel.GenerateId = model.Id;
                                        reportModel.ReportCode = model.TableCode;
                                        reportModel.TimesCycle = model.CycleValue + "月";
                                        reportModel.ReportName = DataDict.Instance["ReportYear"][model.CreateYear] + reportModel.TimesCycle + DataDict.Instance["ReportTableName"][model.TableCode];
                                        reportModel.TimesType = model.Cycle;
                                        reportModel.Status = "1";
                                        reportList.Add(reportModel);
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                        //生成记录表
                        dbCon.Execute(strSql, model, trans);
                        //报表
                        string strReportSql = GetReportSql();
                        dbCon.Execute(strReportSql, reportList, trans);
                        //提交事务
                        trans.Commit();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "添加成功！";
                        dbCon.Dispose();//数据库连接释放
                        return obj;
                    }
                    catch (Exception ex)
                    {
                        obj.status = DefaultKey.ErrorResult;
                        obj.message = ex.ToString().Trim();
                        //出现异常，事务Rollback
                        trans.Rollback();
                        LogHelper.ErrorLog("新增填报生成记录表T_GenerateLog对象信息失败", ex);
                        return obj;
                    }
                }
                else
                {
                    obj.status = DefaultKey.InfoResult;
                    obj.message = "已生成过相同记录数据或者已生成了包含的数据!";
                    return obj;
                }
            }
            #endregion
        }
        public bool CheckGenerate(GenerateLogEntity model)
        {
            string strSql = "select count(1) from dbo.T_GenerateLog where TableName=@TableName";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                int result = dbCon.Query<int>(strSql, new { TableName = model.TableName }).FirstOrDefault();
                if (result > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        public override ResResult<int> DeleteInfo(string id)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"delete from dbo.T_GenerateLog where Id = @Id";
            string strRepSql = @"delete from dbo.T_Report where GenerateId = @GenerateId";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                try
                {
                    dbCon.Execute(strSql, new { Id = id }, trans);
                    dbCon.Execute(strRepSql, new { GenerateId = id }, trans);
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "删除成功！";
                    //提交事务
                    trans.Commit();
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("删除填报生成记录表T_GenerateLog对象信息失败", ex);
                    //出现异常，事务Rollback
                    trans.Rollback();
                    return obj;
                }
            }
        }
        public ResResult<int> Locked(string id)
        {
            ResResult<int> obj = new ResResult<int>();
            string strRepSql = @"UPDATE dbo.T_Report set Status = @Status where GenerateId = @GenerateId";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                try
                {
                    dbCon.Execute(strRepSql, new { GenerateId = id, Status = "5" });
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "锁定成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("锁定填报生成记录表T_GenerateLog对象信息失败", ex);
                    return obj;
                }
            }
        }
        public string GetReportSql()
        {
            string strSql = @"INSERT INTO dbo.T_Report";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportName,";
            strSql += "ReportCode,";
            strSql += "FillInYear,";
            strSql += "TimesType,";
            strSql += "TimesCycle,";
            strSql += "AreaCode,";
            strSql += "Status,";
            strSql += "AddUser,";
            strSql += "AddTime,";
            strSql += "UpdateUser,";
            strSql += "UpdateTime,";
            strSql += "GenerateId)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportName,";
            strSql += "@ReportCode,";
            strSql += "@FillInYear,";
            strSql += "@TimesType,";
            strSql += "@TimesCycle,";
            strSql += "@AreaCode,";
            strSql += "@Status,";
            strSql += "@AddUser,";
            strSql += "@AddTime,";
            strSql += "@UpdateUser,";
            strSql += "@UpdateTime,";
            strSql += "@GenerateId)";
            return strSql;
        }
    }
}